package ext.generic.wfaugment;

import java.io.FileInputStream;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.Vector;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import wt.change2.WTChangeIssue;
import wt.change2.WTChangeOrder2;
import wt.change2.WTChangeRequest2;

import wt.doc.WTDocument;

import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;

import wt.inf.container.WTContained;
import wt.inf.container.WTContainer;
import wt.inf.library.WTLibrary;
import wt.inf.team.ContainerTeam;
import wt.inf.team.ContainerTeamHelper;
import wt.inf.team.ContainerTeamManaged;

import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;

import wt.part.WTPart;

import wt.pdmlink.PDMLinkProduct;

import wt.project.Role;

import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;

import wt.session.SessionHelper;
import wt.session.SessionServerHelper;

import wt.team.Team;

import wt.util.WTException;
import wt.util.WTMessage;
import wt.util.WTProperties;

import wt.vc.baseline.ManagedBaseline;

import wt.workflow.definer.WfAssignedActivityTemplate;
import wt.workflow.definer.WfProcessTemplate;
import wt.workflow.engine.ProcessData;
import wt.workflow.engine.WfActivity;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfVariable;
import wt.workflow.work.WfActorRoleAssignee;
import wt.workflow.work.WfAssignedActivity;
import wt.workflow.work.WfPrincipalAssignee;
//import ext.com.workflow.WorkflowUtil;
import ext.generic.wfaugment.processors.ReadReviewGuideUtil;
import ext.generic.wfaugment.processors.WfAugmentUtil;

public class WorkFlowStepUtil
{

    public static WTProperties wtproperties;
    private static boolean VERBOSE = false;
    private static String CLASSNAME = WorkFlowStepUtil.class.getName();
    private static String RESOURCE = "ext.generic.wfaugment.workflowStepRB";
    public static String activelabel = "";
    public static String userlabel = "";
    public static String selectablelabel = "";
    static
    {
        wtproperties = null;
        try
        {
            wtproperties = WTProperties.getLocalProperties();
            VERBOSE = wtproperties.getProperty("ext.generic.workflowSteps.verbose", false);
            activelabel = WTMessage.getLocalizedMessage(RESOURCE, "ACTIVENAMEDISPLAY", null);
            userlabel = WTMessage.getLocalizedMessage(RESOURCE, "USERNAMEDISPAY", null);
            selectablelabel = WTMessage.getLocalizedMessage(RESOURCE, "IS_SELECTABLE", null);
        }
        catch (Throwable throwable)
        {
            throw new ExceptionInInitializerError(throwable);
        }
    }

    /**
     *输出调试信息
     */
    private static void outDebugInfo(String info)
    {
        if (VERBOSE)
            System.out.println(CLASSNAME + "......" + info);
    }

    /**
     * 读取指定流程实例中对应的流程模板的活动节点
     * @param wfprocess 流程实例
     * @return Vector 流程模板的活动节点
     */
    public static Vector getAllActivitysInTemplate(WfProcess wfprocess) throws WTException
    {
        outDebugInfo("  getAllActivitysInTemplate begin");
        Vector atVc = new Vector();
        Vector atVc2 = new Vector();
        WfProcessTemplate wfprocesstemplate = (WfProcessTemplate) wfprocess.getTemplate().getObject();
        for (QueryResult queryresult = PersistenceHelper.manager.navigate(wfprocesstemplate, "step", wt.workflow.definer.ProcessStepTemplateLink.class);
             queryresult.hasMoreElements(); )
        {
            Object obj = queryresult.nextElement();
            if (obj instanceof WfAssignedActivityTemplate)
            {
                atVc.add(obj);
                atVc2.add(((WfAssignedActivityTemplate) obj).getName());
            }
        }
        outDebugInfo("  getAllActivitysInTemplate WfAssignedActivityTemplate atVc2=" + atVc2);
        return atVc;
    }

    /**
     * 读取指定流程实例中对应的流程模板的活动节点
     * @param wfprocess 流程实例
     * @return Vector 流程模板的活动节点1
     */
    public static Vector getAllActivitysInProcess(WfProcess wfprocess) throws WTException
    {
        outDebugInfo("  getAllActivitysInTemplate begin");
        Vector atVc = new Vector();
        Vector atVc2 = new Vector();
        WfProcessTemplate wfprocesstemplate = (WfProcessTemplate) wfprocess.getTemplate().getObject();
        for (QueryResult queryresult = PersistenceHelper.manager.navigate(wfprocesstemplate, "step", wt.workflow.definer.ProcessStepTemplateLink.class);
             queryresult.hasMoreElements(); )
        {
            Object obj = queryresult.nextElement();
            if (obj instanceof WfAssignedActivityTemplate)
            {
                atVc.add(obj);
                atVc2.add(((WfAssignedActivityTemplate) obj).getName());
            }
        }
        outDebugInfo("  getAllActivitysInTemplate WfAssignedActivityTemplate atVc2=" + atVc2);
        return atVc;
    }

    /**
     * 读取流程实例对应的模板的活动节点
     * @param wfprocess 流程实例
     * @return Hashtable key:模板活动节点的名称，Value：活动对象
     */
    public static Hashtable getAllActivitysHashtableInProcess(WfProcess wfprocess) throws WTException
    {
        outDebugInfo("  getAllActivitysHashtableInProcess begin");
        Hashtable ht = new Hashtable();
        Enumeration enSteps = WfEngineHelper.service.getProcessSteps(wfprocess, null);
        String activename = "";
        while (enSteps.hasMoreElements())
        {
            WfActivity act = (WfActivity) enSteps.nextElement();
            if (act instanceof WfAssignedActivity)
            {
                activename = act.getName();
                ht.put(activename, act);
                outDebugInfo(" getAllActivitysHashtableInProcess activename= " + activename);
            }
        }
        return ht;
    }

    /**
     * 读取指定流程实例中对应的流程模板的活动节点及负责角色
     * @param wfprocess 流程实例
     * @return Hashtable 流程模板的活动节点  key:模板活动节点，Value：负责的角色（单个角色）
     */
    public static Hashtable getAllActivitysAndRoleInTemplate(WfProcess wfprocess, Persistable persistable) throws WTException
    {
        outDebugInfo("  getAllActivitysAndRoleInTemplate begin");
        Hashtable ht = new Hashtable();
        WfProcessTemplate wfprocesstemplate = (WfProcessTemplate) wfprocess.getTemplate().getObject();
        for (QueryResult queryresult = PersistenceHelper.manager.navigate(wfprocesstemplate, "step", wt.workflow.definer.ProcessStepTemplateLink.class);
             queryresult.hasMoreElements(); )
        {
            Object obj = queryresult.nextElement();
            if (obj instanceof WfAssignedActivityTemplate)
            {
                WfAssignedActivityTemplate wft = (WfAssignedActivityTemplate) obj;
                //如果有角色负责，则直接读取第一个角色，
                Role role = null;
                Enumeration enums = wft.getRoles();
                while (enums.hasMoreElements())
                {
                    role = (Role) enums.nextElement();
                    break;
                }
                if (role != null)
                {
                    ht.put(wft, role);
                    outDebugInfo(" getAllActivitysAndRoleInTemplate activename= " + wft.getName() + "  role=" + role.toString());
                }
                //如果不是角色，则读取 创建者全称
                else
                {
                    WfActorRoleAssignee actra = null;
                    Enumeration emu2 = wft.getActorRoleAssignees();
                    while (emu2.hasMoreElements())
                    {
                        actra = (WfActorRoleAssignee) emu2.nextElement();
                        if (actra != null)
                        {
                            ht.put(wft, actra);
                            break;
                        }
                    }
                    if (actra == null)
                    {
                        StringBuffer strb = new StringBuffer("");
                        Enumeration emu = wft.getPrincipalAssignees();
                        while (emu.hasMoreElements())
                        {
                            WTPrincipal wtp = ((WfPrincipalAssignee) emu.nextElement()).getPrincipal().getPrincipal();
                            strb.append(((WfPrincipalAssignee) emu.nextElement()).getPrincipal().getFullName() + "\n");
                        }
                        ht.put(wft, strb.toString());
                    }
                }
            }
        }
        return ht;
    }

    /**
     * 读取指定Sheet中指定活动名称的签审信息，同时构造出签审环节
     * 读取流程实例对应的模板的活动节点
     * @param pbo 流程主对象
     * @param wfprocess 流程实例
     * @return Hashtable key:模板活动节点，Value：签审表中该活动节点的配置信息
     */
    public static Hashtable getWorkFlowStepInReviewGuideByTemplate(Persistable pbo, WfProcess wfprocess) throws WTException
    {
        Hashtable ht = new Hashtable();
        try
        {
            outDebugInfo(".getWorkFlowStepInReviewGuide() pbo=" + ((WTObject) pbo).getDisplayIdentifier());
            String wfConfigFilePath = WfAugmentUtil.getConfigFilePath(pbo);
            outDebugInfo("\t 签审指南路径=" + wfConfigFilePath);
            if (wfConfigFilePath == null || wfConfigFilePath.length() == 0)
                return null;
            XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(wfConfigFilePath));
            if (wb == null)
                return null;
            XSSFSheet sheet = wb.getSheetAt(0);
            if (sheet == null)
                return null;
            int rowNumber = 0;
            if (pbo instanceof WTDocument)
            {
                WTDocument doc = (WTDocument) pbo;
                rowNumber = ReadReviewGuideUtil.getConfigLineInGuide(doc, sheet);
            }
            else if (pbo instanceof WTPart)
            {
                WTPart part = (WTPart) pbo;
                rowNumber = ReadReviewGuideUtil.getConfigLineInGuide(part, sheet);
            }
            else if (pbo instanceof WTChangeOrder2)
            {
                WTChangeOrder2 ecn = (WTChangeOrder2) pbo;
                rowNumber = ReadReviewGuideUtil.getConfigLineInGuide(ecn, sheet);
            }

            // 问题报告流程
            else if (pbo instanceof WTChangeIssue)
            {
                WTChangeIssue eci = (WTChangeIssue) pbo;
                rowNumber = ReadReviewGuideUtil.getConfigLineInGuide(eci, sheet);
            }
            else
            {
                rowNumber = 1;
            }
            outDebugInfo("\t rowNumber = " + rowNumber);
            String cellValue = "";
            XSSFRow row;
            XSSFCell cell;
            String activename;
            XSSFRow row1;
            String roleValue;
            // 获取第一行，判断签审环节
            row = sheet.getRow(0);
            Vector activetysVc = getAllActivitysInTemplate(wfprocess);
            for (int k = 0; k < activetysVc.size(); k++)
            {
                WfAssignedActivityTemplate wft = (WfAssignedActivityTemplate) activetysVc.elementAt(k);
                activename = wft.getName();
                for (int i = 0; i < row.getLastCellNum(); i++)
                {
                    cell = row.getCell((short) i);
                    if (cell == null)
                        continue;
                    cellValue = cell.getStringCellValue().trim();
                    if (cellValue.length() > 0 && cellValue.equals(activename))
                    {
                        outDebugInfo(" activityName=" + activename + " rowNumber = " + rowNumber + " culmNumber=" + i);
                        row1 = sheet.getRow(rowNumber);
                        cell = row1.getCell((short) i);
                        roleValue = cell.getStringCellValue();
                        outDebugInfo(" roleValue=" + roleValue);
                        if (roleValue != null)
                        {
                            roleValue = roleValue.trim();
                            if (roleValue.length() > 0)
                            {
                                ht.put(wft, roleValue);
                                break;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new WTException(e);
        }
        return ht;
    }

    /**
     * 读取指定Sheet中指定活动名称的签审信息，同时构造出签审环节
     * @param pbo 流程主对象
     * @param wfprocess 流程实例
     * @return Hashtable key:模板活动节点的名称，Value：签审表中该活动节点配置的信息
     */
    public static Hashtable getWorkFlowStepInReviewGuideByName(Persistable pbo, WfProcess wfprocess) throws WTException
    {
        Hashtable ht = new Hashtable();
        try
        {
            outDebugInfo(".getWorkFlowStepInReviewGuide() pbo=" + ((WTObject) pbo).getDisplayIdentifier());
            String wfConfigFilePath = WfAugmentUtil.getConfigFilePath(pbo);
            outDebugInfo("\t 签审指南路径=" + wfConfigFilePath);
            if (wfConfigFilePath == null || wfConfigFilePath.length() == 0)
                return null;
            XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(wfConfigFilePath));
            if (wb == null)
                return null;
            XSSFSheet sheet = wb.getSheetAt(0);
            if (sheet == null)
                return null;
            int rowNumber = 0;
            if (pbo instanceof WTDocument)
            {
                WTDocument doc = (WTDocument) pbo;
                rowNumber = ReadReviewGuideUtil.getConfigLineInGuide(doc, sheet);
            }
            else if (pbo instanceof WTPart)
            {
                WTPart part = (WTPart) pbo;
                rowNumber = ReadReviewGuideUtil.getConfigLineInGuide(part, sheet);

            }
            else if (pbo instanceof WTChangeOrder2)
            {
                WTChangeOrder2 ecn = (WTChangeOrder2) pbo;
                rowNumber = ReadReviewGuideUtil.getConfigLineInGuide(ecn, sheet);
            }
            // 问题报告流程
            else if (pbo instanceof WTChangeIssue)
            {
                WTChangeIssue eci = (WTChangeIssue) pbo;
                rowNumber = ReadReviewGuideUtil.getConfigLineInGuide(eci, sheet);
            }
            else
            {
                rowNumber = 1;
            }
            outDebugInfo("\t rowNumber = " + rowNumber);
            String cellValue = "";
            XSSFRow row;
            XSSFCell cell;
            String activename;
            XSSFRow row1;
            String roleValue;
            // 获取第一行，判断签审环节
            row = sheet.getRow(0);
            Vector activetysVc = getAllActivitysInTemplate(wfprocess);
            for (int k = 0; k < activetysVc.size(); k++)
            {
                WfAssignedActivityTemplate wft = (WfAssignedActivityTemplate) activetysVc.elementAt(k);
                activename = wft.getName();
                for (int i = 0; i < row.getLastCellNum(); i++)
                {
                    cell = row.getCell((short) i);
                    if (cell == null)
                        continue;
                    cellValue = cell.getStringCellValue().trim();
                    if (cellValue.length() > 0 && cellValue.equals(activename))
                    {
                        outDebugInfo(" activityName=" + activename + " rowNumber = " + rowNumber + " culmNumber=" + i);
                        row1 = sheet.getRow(rowNumber);
                        cell = row1.getCell((short) i);
                        roleValue = cell.getStringCellValue();
                        outDebugInfo(" roleValue=" + roleValue);
                        if (roleValue != null)
                        {
                            roleValue = roleValue.trim();
                            if (roleValue.length() > 0)
                            {
                                ht.put(activename, roleValue);
                                break;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new WTException(e);
        }
        return ht;
    }

    /**
     * 将用;;;qqq分割的字符串转化为向量
     * @param augmentRolesStr 用;;;qqq分割的字符串
     * @return Vector 通过;;;qqq分割后的字符向量
     */
    public static Vector parseRoleStr(String augmentRolesStr)
    {
        Vector v = new Vector();
        StringTokenizer st = new StringTokenizer(augmentRolesStr, ";;;qqq");
        while (st.hasMoreTokens())
        {
            v.addElement(st.nextToken());
        }
        return v;
    }

    /**
     * 读取指定指定活动中能够设置的角色
     * @param wfactivity 指定的活动
     * @return Vector 指定的活动节点可以设置的角色
     */
    public static Vector getNeedSetRole(WfActivity wfactivity) throws WTException
    {
        Vector needset = new Vector();
        String augmentRolesName = WfAugmentUtil.getPropertiesValue("ext.generic.wfaugment.wfaugment", "wf.roles.vector");
        if (augmentRolesName == null || augmentRolesName.trim().length() == 0)
            augmentRolesName = "augmentRoles";
        if (wfactivity == null)
            return needset;
        String needstr = null;
        ProcessData processdata = wfactivity.getContext();
        if (processdata != null)
        {
            needstr = (String) processdata.getValue(augmentRolesName);
            if (needstr != null && needstr.trim().length() > 0)
            {
                needset = parseRoleStr(needstr);
            }
        }
        return needset;
    }

    /**
     * 读取指定指定活动中能够设置的角色
     * @param wfactivity 指定的活动
     * @return boolean  true:指定的活动节点可以设置的角色
     */
    public static boolean getSetable(WfActivity wfactivity) throws WTException
    {
        boolean setable = false;
        String setablestr = WfAugmentUtil.getPropertiesValue("ext.generic.wfaugment.wfaugment", "wf.roles.setable");
        if (setablestr == null || setablestr.trim().length() == 0)
            setablestr = "setable";
        if (wfactivity == null)
            return setable;
        ProcessData processdata = wfactivity.getContext();
        if (processdata != null)
        {
            WfVariable wfvariable1 = processdata.getVariable(setablestr);
            if (wfvariable1 != null)
            {
                String s5 = wfvariable1.getTypeName();
                if (s5.equals("java.lang.Boolean") || s5.equals("boolean"))
                {
                    setable = ((Boolean) wfvariable1.getValue()).booleanValue();
                }
            }
        }
        return setable;
    }

    /**
     * 读取指定指定活动中能够设置的角色
     * @param wfactivity 指定的活动
     * @return boolean  true:指定的活动节点可以设置的角色
     */
    public static ArrayList getUserInTheContainerTeam(Persistable persistable, String rolestr) throws WTException
    {
        ArrayList arraylist = new ArrayList();
        if (persistable == null || rolestr == null || rolestr.toString().length() == 0)
            return arraylist;
        outDebugInfo(" persistable == " + persistable);
        outDebugInfo(" rolestring == " + rolestr);
        boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
        try
        {
            if (persistable instanceof WTContained)
            {
                WTContained containedObj = (WTContained) persistable;
                WTContainer container = containedObj.getContainer();
                if (container instanceof ContainerTeamManaged)
                {
                    ContainerTeam containerTeam = ContainerTeamHelper.service.getContainerTeam((ContainerTeamManaged) container);

                    if (rolestr != null && rolestr.length() > 0)
                    {
                        rolestr = rolestr.substring(1);
                        // 分开产品团队和普通的用户组
                        StringTokenizer token = new StringTokenizer(rolestr, "|");
                        while (token.hasMoreElements())
                        {
                            String temp1 = token.nextToken();
                            temp1 = temp1.trim();
                            if (temp1.startsWith("R"))
                            {
                                if (temp1.length() > 2)
                                {
                                    temp1 = temp1.substring(2);
                                    temp1 = temp1.trim();
                                    StringTokenizer token2 = new StringTokenizer(temp1, ",");
                                    while (token2.hasMoreElements())
                                    {
                                        String temp2 = token2.nextToken();
                                        temp2 = temp2.trim();
                                        outDebugInfo("  temprole=  " + temp2);
                                        ArrayList participants = containerTeam.getAllPrincipalsForTarget(Role.toRole(temp2));
                                        if (participants != null)
                                        {
                                            for (int j = 0; j < participants.size(); j++)
                                            {
                                                wt.org.WTPrincipal wtp = ((wt.org.WTPrincipalReference) participants.get(j)).getPrincipal();
                                                outDebugInfo(" role WTPrincipal=  " + wtp.getDisplayIdentifier());
                                                arraylist.add(wtp);
                                            }
                                        }
                                    }
                                }
                            }
                            if (temp1.startsWith("G"))
                            {
                                if (temp1.length() > 2)
                                {
                                    temp1 = temp1.substring(2);
                                    temp1 = temp1.trim();
                                    // 分开每一个组
                                    StringTokenizer token3 = new StringTokenizer(temp1, ",");
                                    while (token3.hasMoreElements())
                                    {
                                        String temp3 = token3.nextToken();
                                        temp3 = temp3.trim();
                                        WTGroup wtgroup = getGroupByName(temp3);
                                        outDebugInfo("  WTGroup=  " + temp3);
                                        if (wtgroup != null)
                                        {
                                            Enumeration members = wtgroup.members();
                                            while (members != null && members.hasMoreElements())
                                            {
                                                wt.org.WTPrincipal wtp = ((wt.org.WTPrincipal) members.nextElement());
                                                arraylist.add(wtp);
                                                outDebugInfo(" wtgroup WTPrincipal=  " + wtp.getDisplayIdentifier());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }
        outDebugInfo(" final return  == " + arraylist);
        return arraylist;
    }

    /**
     * 通过名称读取系统组
     * @param groupName 组的名称
     * @return WTGroup 跟名称一样的租
     */
    public static WTGroup getGroupByName(String groupName) throws QueryException, WTException
    {
        WTGroup wtgroup = null;
        QuerySpec qs = null;
        QueryResult qr = null;
        qs = new QuerySpec(WTGroup.class);
        SearchCondition sc = new SearchCondition(WTGroup.class, "name", "=", groupName);
        qs.appendSearchCondition(sc);
        qr = PersistenceHelper.manager.find(qs);
        while (qr.hasMoreElements())
        {
            wtgroup = (WTGroup) qr.nextElement();
            break;
        }
        return wtgroup;
    }

    /**
     * 读取流程团队中所有角色的成员
     * @param self 活动节点
     * @return Hashtable 团队角色的成员 key:角色 value:用户
     */
    public static Hashtable getRoleMemberInteam(Object self) throws WTException
    {
        Hashtable ht = new Hashtable();
        if (self == null)
            return ht;
        WfProcess wfprocess = null;
        //wfprocess = WorkflowUtil.getProcess(self);
        if (wfprocess == null)
            return ht;
        //读取了流程团队
        wt.team.Team team = (wt.team.Team) ((wt.team.TeamReference) ((wt.team.TeamManaged) wfprocess).getTeamId()).getObject();
        if (team == null)
            return ht;
        Vector rolevc = team.getRoles();
        if (rolevc == null)
            return ht;
        for (int i = 0; i < rolevc.size(); i++)
        {
            Role role = (Role) rolevc.get(i);
            Enumeration enums = team.getPrincipalTarget(role);
            StringBuffer userbf = new StringBuffer("");
            while (enums != null && enums.hasMoreElements())
            {
                WTPrincipalReference principalRef = (WTPrincipalReference) enums.nextElement();
                if (principalRef == null || principalRef.isDisabled())
                    continue;
                userbf.append(principalRef.getPrincipal().getName() + ";");
            }
            ht.put(role.toString(), userbf.toString());
        }
        return ht;
    }

    /**
     * 拷贝流程团队中某个角色的成员到另一个角色中
     * @param self 活动节点
     * @param roleA 原始角色，
     * @param roleB 目标角色
     */
    public static void copyRoleToOtherRole(Object self, String roleA, String roleB) throws WTException
    {
        boolean flag = SessionServerHelper.manager.setAccessEnforced(false);

        try
        {
            if (self == null)
                return;
            WfProcess wfprocess = null;
            //wfprocess = WorkflowUtil.getProcess(self);
            if (wfprocess == null)
                return;
            //读取了流程团队
            wt.team.Team team = (wt.team.Team) ((wt.team.TeamReference) ((wt.team.TeamManaged) wfprocess).getTeamId()).getObject();
            if (team == null)
                return;
            Role rB = Role.toRole(roleB);
            Role rA = Role.toRole(roleA);
            Enumeration rmenums = team.getPrincipalTarget(Role.toRole(roleB));
            while (rmenums != null && rmenums.hasMoreElements())
            {
                WTPrincipal wtp = ((WTPrincipalReference) rmenums.nextElement()).getPrincipal();
                team.deletePrincipalTarget(rB, wtp);
                outDebugInfo(" copyRoleToOtherRole delete WTPrincipal=" + wtp.getDisplayIdentifier() + " from role=" + rB);
            }
            Enumeration addenums = team.getPrincipalTarget(Role.toRole(roleA));
            while (addenums != null && addenums.hasMoreElements())
            {
                WTPrincipal wtpforadd = ((WTPrincipalReference) addenums.nextElement()).getPrincipal();
                team.addPrincipal(rB, wtpforadd);
                outDebugInfo(" copyRoleToOtherRole add WTPrincipal=" + wtpforadd.getDisplayIdentifier() + " from role=" + rB);
            }
            team = (Team) PersistenceHelper.manager.refresh(team);
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }

    }

    /**
     * 读取某个角色归属到库下的哪个角色
     * @param container 容器库
     * @param user 用户
     * @return StringBuffer 目标角色
     */
    public static StringBuffer getRolesOfUser(WTContainer container, WTPrincipal user) throws WTException
    {
        boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
        outDebugInfo("   getRolesOfUser      container========" + container);
        StringBuffer stbf = new StringBuffer("");
        try
        {
            Locale locale = SessionHelper.getLocale();
            if (!(container instanceof PDMLinkProduct) && !(container instanceof WTLibrary))
                return stbf;
            ContainerTeam containerteama = ContainerTeamHelper.service.getContainerTeam((ContainerTeamManaged) container);
            WTPrincipalReference wtprincipalreference = WTPrincipalReference.newWTPrincipalReference(user);

            HashMap hashmap = containerteama.getAllMembers();
            //读取了流程团队
            ArrayList arraylist = (ArrayList) hashmap.get(wtprincipalreference);
            if (arraylist != null)
            {
                for (int i = 0; i < arraylist.size(); i++)
                {
                    Role role = (Role) arraylist.get(i);
                    stbf.append(role.getDisplay(locale) + ",");
                }
            }
            if (stbf.lastIndexOf(",") > 0)
                stbf.deleteCharAt(stbf.lastIndexOf(","));
            return stbf;
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }

    }

}
